<template>
	<view class="container" :style="{ height: `calc(100vh - ${tabHeight}px)` }">
		<view class="content">
			<!-- 新增容器，用于包裹商品类别列表 -->
			<view class="category-container">
				<view class="category-list">
					<view class="category-item" v-for="(category, index) in productCategoryList" :key="index"
						:class="{ active: selectedCategory === category.id }" @click="selectCategory(category)">
						<text class="category-name">{{ category.categoryName }}</text>
					</view>
				</view>
			</view>
			<view class="product-list">
				<store-product v-for="(product, index) in currentProducts" :key="index" appid="wxe9094455e312c8ce"
					:product-id="product.productId" />
			</view>
		</view>

		<use-tabber id="tabberId" :list="list" :active="active"></use-tabber>
	</view>
</template>

<script>
	import {
		ref,
		reactive,
		nextTick
	} from 'vue';
	import {
		onShow,
		onLoad
	} from '@dcloudio/uni-app';
	import {
		product
	} from '@/api/product.js';
	import {
		useStore
	} from '@/store/counter.js';

	export default {
		setup() {
			const store = useStore();
			const list = ref([]);
			const active = ref(1);
			const tabHeight = ref(0);

			const productCategoryList = ref([]);
			const wechatStoreProductsDtoList = ref([]);
			const productsByCategory = ref({});
			const selectedCategory = ref('');
			const currentProducts = ref([]);

			const selectCategory = async (category) => {
				selectedCategory.value = category.id;
				currentProducts.value = []; // 清空原有数据

				await nextTick(); // 等待DOM更新

				const categoryId = String(category.id);
				const products = productsByCategory.value[categoryId];

				if (!products) {
					console.warn(`类别ID ${categoryId} 无匹配数据`);
					return;
				}

				currentProducts.value = [...products]; // 触发响应式更新
			};

			onLoad(async () => {
				console.log('onLoad 事件已触发');
				await loadData();
			});

			onShow(async () => {
				console.log('onShow 事件已触发');
				list.value = store.getRole();
				await loadData();
			});

			const loadData = async () => {
				try {
					const res = await product.getProduct();
					const query = uni.createSelectorQuery();
					query.select('#tabberId').boundingClientRect(rect => {
						tabHeight.value = rect.height;
					}).exec();

					productCategoryList.value = res.data.productCategoryList || [];
					wechatStoreProductsDtoList.value = res.data.wechatStoreProductsDtoList || [];

					// 统一使用字符串类型匹配类别ID
					productsByCategory.value = wechatStoreProductsDtoList.value.reduce((acc, product) => {
						const productTypeId = String(product.type);
						const category = productCategoryList.value.find(c => String(c.id) ===
							productTypeId);

						if (category) {
							acc[category.id] = acc[category.id] || [];
							acc[category.id].push(product);
						} else {
							console.warn(`产品类型 ${productTypeId} 无对应类别`);
						}
						return acc;
					}, {});

					// 页面加载时默认选中第一个类别
					if (productCategoryList.value.length > 0) {
						const firstCategory = productCategoryList.value[0];
						selectedCategory.value = firstCategory.id; // 设置选中状态

						// 延迟确保响应式更新完成（可选，根据实际情况调整）
						setTimeout(() => {
							currentProducts.value = [...productsByCategory.value[firstCategory.id] || []];
						}, 50);

						console.log('默认选中类别:', firstCategory.categoryName);
					} else {
						currentProducts.value = [];
					}
				} catch (error) {
					console.error('获取数据失败:', error);
					currentProducts.value = [];
				}
			};

			return {
				productCategoryList,
				currentProducts,
				selectedCategory,
				selectCategory,
				list,
				active,
				tabHeight
			};
		}
	};
</script>

<style>
	/* 整合后的样式 */
	.container {
		padding: 20px;
		background-color: #f9f9f9;
	}

	.content {
		gap: 20px;
	}

	/* 新增容器样式 */
	.category-container {
		width: 100%;
		overflow-x: auto;
		-webkit-overflow-scrolling: touch;
		white-space: nowrap;
	}

	.category-list {
		display: flex;
	}

	.category-section-title {
		font-size: 20px;
		font-weight: bold;
		color: #333;
		text-align: center;
		margin-bottom: 20px;
	}

	.category-item {
		width: 200px;
		padding: 15rpx;
		margin: 9rpx;
		background-color: white;
		border-radius: 16rpx;
		cursor: pointer;
		transition: all 0.3s ease;
		text-align: center;
		color: #333;
		height: 100%;
		line-height: 24px;
		font-size: 10px;
		display: inline-block;
	}

	.category-item:hover {
		transform: scale(1.05);
		background-color: #e9e9e9;
	}

	.category-item.active {
		background-color: #007bff;
		color: white;
		width: 200px;
		height: 100%;
		line-height: 24px;
		font-size: 10px;
	}

	.category-name {
		font-size: 14px;
	}

	.product-list {
		/* width: 68%; */
		display: flex;
		flex-direction: column;
		gap: 20px;
	}

	.product-item {
		background-color: #ffffff;
		border-radius: 10px;
		padding: 15px;
		box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
		transition: transform 0.3s;
		display: flex;
		gap: 15px;
	}

	.product-item:hover {
		transform: scale(1.05);
	}

	.product-image {
		width: 80px;
		/* 修改宽度 */
		height: 80px;
		/* 修改高度 */
		object-fit: cover;
		border-radius: 8px;
		min-width: 80px;
		/* 修改最小宽度 */
		max-width: 80px;
		/* 修改最大宽度 */
		min-height: 80px;
		/* 修改最小高度 */
		max-height: 80px;
		/* 修改最大高度 */
	}

	.product-info {
		display: flex;
		flex-direction: column;
		justify-content: center;
		gap: 10px;
	}

	.product-name {
		font-size: 16px;
		font-weight: bold;
		color: #333;
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 2;
		overflow: hidden;
	}

	.product-spec {
		font-size: 14px;
		color: #ff8c00;
		margin-top: 5px;
	}

	/* 导航栏样式 */
	.use-tabber {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 50px;
		background-color: white;
		border-top: 1px solid #e4e4e4;
	}
</style>